from flask import Flask, request, jsonify
from flask_mysqldb import MySQL
import requests

app = Flask(__name__)

# Configure MySQL Connection
app.config['MYSQL_HOST'] = '3306'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'wanglibo123..'
app.config['MYSQL_DB'] = 'Song'

mysql = MySQL(app)

@app.route('/search_and_download', methods=['GET'])
def search_and_download():
    key = request.args.get('key', '')
    total_pages = int(request.args.get('total_pages', '1'))
    pageSize = request.args.get('pageSize', '20')
    t = request.args.get('t', '0')

    for pageNo in range(1, total_pages + 1):
        api_url = f"http://127.0.0.1:3300/search?key={key}&pageNo={pageNo}&pageSize={pageSize}&t={t}"
        try:
            response = requests.get(api_url)
            response.raise_for_status()
            data = response.json()
            songs = data.get('data', {}).get('list', [])
            for song in songs:
                song_data = {
                    'songname': song.get('songname', ''),
                    'albumname': song.get('albumname', ''),
                    'singer': ', '.join([singer.get('name', '') for singer in song.get('singer', [])]),
                    'songmid': song.get('songmid', ''),
                    'download_link': f"http://127.0.0.1:5000/download/{song.get('songmid', '')}"
                }
                # Insert song data into database
                cursor = mysql.connection.cursor()
                sql = """INSERT INTO Songs (songname, albumname, singer, songmid, download_link)
                         VALUES (%s, %s, %s, %s, %s)"""
                cursor.execute(sql, (song_data['songname'], song_data['albumname'], song_data['singer'], song_data['songmid'], song_data['download_link']))
                mysql.connection.commit()
                cursor.close()
        except requests.exceptions.RequestException as e:
            return jsonify({'error': str(e), 'message': 'Failed to fetch data from API'}), 500

    return jsonify({'message': 'Data fetched and stored successfully'})

if __name__ == '__main__':
    app.run(debug=True)
